package com.zqq.webcloud;

import android.util.Log;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 这是一种
 * HttpURLConnection使用步骤：
 * 1.实例化URL对象；
 * 2.实例化HttpUrlConnection对象；
 * 3.设置请求连接属性，传递参数等；
 * 4.获取返回码判断是否链接成功；
 * 5.读取输入流；
 * 6.关闭链接。
 *
 * @author zqq on 2018/9/6
 */
public class HttpURLConnectionNetworkTask extends NetworkTask {

    public HttpURLConnectionNetworkTask(String method) {
        super(method);
    }

    @Override
    public String doGet(String httpUrl) {
        String result;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            //HttpURLConnection默认就是用GET发送请求，所以下面的setRequestMethod可以省略
            conn.setRequestMethod("GET");
            //HttpURLConnection默认也支持从服务端读取结果流，所以下面的setDoInput也可以省略
            conn.setDoInput(true);
            //禁用网络缓存
            conn.setUseCaches(false);

            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);

            //设置请求头
            //用setRequestProperty方法设置一个自定义的请求头
            conn.setRequestProperty("Charset", "UTF-8");
            conn.setRequestProperty("Content-Type", "application/json");
            conn.setRequestProperty("X-LC-Id", "LiGEddCUfS94R9VBfpww9mWO-gzGzoHsz");
            conn.setRequestProperty("X-LC-Key", "1YVHJJqtSrU50RGK7fH7MT87");

            Log.e("--Taf----", conn.getHeaderFields().toString());

            if (conn.getResponseCode() == 200) {
                InputStream inputStream = conn.getInputStream();
                result = readFromStream(inputStream);

            } else {
                isSuccess = false;
                result = "网络响应状态码不为200!" + conn.getResponseCode();
            }
        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
            result = "网络访问错误:" + e.getMessage();
        }
        return result;
    }

    /**
     * 输入流获取字符串
     *
     * @param inputStream 输入流
     * @return String 返回的字符串
     * @throws IOException
     */
    private String readFromStream(InputStream inputStream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[2014];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        inputStream.close();
        String result = baos.toString();

        baos.close();
        return result;
    }

    @Override
    public String doPost(String httpUrl, Map<String, String> paramMap) {
        String result;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();

            conn.setRequestMethod("POST");
            conn.setReadTimeout(5000);
            conn.setConnectTimeout(5000);

            // 配置连接的Content-type
            conn.setRequestProperty("Content-Type", "application/x-form-urlencoded");
            conn.setDoOutput(true);    // 发送POST请求必须设置允许输出
            conn.setDoInput(true);     // 发送POST请求必须设置允许输入

            String data = "";
            boolean firstParam = true;
            for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                if (firstParam) {
                    data += entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
                    firstParam = false;
                } else {
                    data += "&" + entry.getKey() + "=" + URLEncoder.encode(entry.getValue(), "UTF-8");
                }
            }

            //将要上传的内容写入流中
            OutputStream os = conn.getOutputStream();
            os.write(data.getBytes());
            //刷新、关闭
            os.flush();
            os.close();

            if (conn.getResponseCode() == 200) {
                InputStream is = conn.getInputStream();
                result = readFromStream(is);

            } else {
                isSuccess = false;
                result = "网络响应状态码为:" + conn.getResponseCode()+":"+conn.getResponseMessage();

                InputStream is = conn.getErrorStream();
                result = readFromStream(is);

                Log.e("----Tag=", result);
            }

        } catch (Exception e) {
            e.printStackTrace();
            isSuccess = false;
            result = "网络访问错误:" + e.getMessage();
        }
        return result;
    }
}
